package com.qf.filter;

import com.alibaba.fastjson.JSON;
import com.qf.entity.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

@Component
public class CodeFilter implements GatewayFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得验证码的key
        ServerHttpRequest request = exchange.getRequest();
        String uuid = request.getQueryParams().getFirst("uuid");

        //获得用户输入的验证码
        String code = request.getQueryParams().getFirst("code");
        System.out.println("redis中的验证码：" + redisTemplate.opsForValue().get("code_" + uuid) + "  输入的验证码：" + code);
        if (code.equals(redisTemplate.opsForValue().get("code_" + uuid))) {
            //删除验证码
            redisTemplate.delete("code_" + uuid);
            //放行
            return chain.filter(exchange);
        }

        ServerHttpResponse response = exchange.getResponse();

        R result = new R()
                .setCode(R.CODE.ERROR)
                .setMsg("验证码错误！");

        DataBuffer dataBuffer = null;
        try {
            response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
            //解决跨域问题
            response.getHeaders().add("Access-Control-Allow-Origin", "*");
            dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 50;
    }
}
